import 'dart:async';

import 'package:common_utils/common_utils.dart';
import 'package:flutter/foundation.dart';
import 'package:flutter/services.dart';
// import 'package:fluttertoast/fluttertoast.dart';

import 'package:fluwx/fluwx.dart' as fluwx;
import 'package:get/get.dart';
import 'package:intl/intl.dart';
import 'package:logger/logger.dart';
import 'package:sp_util/sp_util.dart';
import 'package:yp/config/config.dart';
import 'package:yp/services/api.dart';
import 'package:yp/utils/util.dart';

import '../../helper.dart';
import 'state.dart';

import 'package:yp/pages/address_selector/address_model.dart';

class OrderSettlementLogic extends GetxController {
  static const platform = const MethodChannel("com.elitesland/pay");
  StreamController _weChatResponseEventHandlerController =
      StreamController.broadcast();

  Stream get weChatResponseEventHandler =>
      _weChatResponseEventHandlerController.stream;
  final state = OrderSettlementState();
  final type = Get.arguments == null ? 1 : Get.arguments['type'];
  var logger = Logger(
    printer: PrettyPrinter(),
  );

  @override
  void onInit() {
    // TODO: implement onInit
    super.onInit();
    // fluwx.weChatResponseEventHandler.listen((event) {
    //   if (event is fluwx.WeChatLaunchMiniProgramResponse) {
    //     /// 取消支付：extMsg:{"errMsg":"requestPayment:fail cancel","status":"30"}
    //     /// 支付成功 extMsg:{"errMsg":"requestPayment:ok","status":"20"}
    //     Map resultMap = json.decode(event.extMsg);
    //     print("支付结果");
    //     print(SpUtil.getString('dingdan'));
    //     if (resultMap != null) {
    //       if (resultMap["status"].toString() == "20") {
    //         toast("支付成功");
    //         setMoneyOver(SpUtil.getString('dingdan'), 1, 'Complete', 'success', 'a');
    //       } else {
    //         toast("支付失败");
    //         setMoneyOver(SpUtil.getString('dingdan'), 0, 'List', 'err', 'a');
    //       }
    //     } else {
    //       setMoneyOver(SpUtil.getString('dingdan'), 0, 'List', 'err', 'a');
    //
    //       toast("支付失败");
    //     }
    //   }
    // });
  }

  @override
  void onReady() {
    // if (type == 1) {
    //   state.type = 3;
    // } else {
    //   state.type = null;
    // }
    // print('params1');
    // print(state.type);
    // TODO: implement onReady
    super.onReady();

    // selfHelpAddress();
    // 默认地址信息
    getGiftCard();
    getCurrentLocationInfo(success: (backInfo) {
      if (backInfo != null) {
        state.orderAddress = backInfo["addressInfo"];
        var params = {
          "usr_num_id": SpUtil.getInt('empeNumId'),
          "use_platform": 2,
          "channel_num_id": 99,
          "tran_type_num_id": 3,
          // "integral_type": 2, // 1是该商品参加积分换购 2是取消
          // "integral_item_list": [200000004595],
          "prv_num_id": state.orderAddress['prv_num_id'],
          "city_num_id": state.orderAddress['city_num_id'],
          "city_area_num_id": state.orderAddress['city_area_num_id'],
          "town_num_id": state.orderAddress['town_num_id'],
          "maplocation_x": state.orderAddress['maplocation_x'],
          "maplocation_y": state.orderAddress['maplocation_y'],
          "adr_num_id": state.orderAddress["adr_num_id"],
          "integral": state.isJiFen ? null : 0,
          "adr_type": state.isZiTi ? 1 : 0,
          'access_token': SpUtil.getString('token'),
          "is_logistics_cart": '1',
        };
        print('printprint');
        print(params);
        Api.orderSettle(params).listen((event) {
          // if (event['total'] != null) {
          //   if (state.orderAddress != null) {
          //     state.orderAddress = event["member_adr"];
          //     state.jiaAddress = event["member_adr"];
          //   }
          // }

          // if (event['integral'] == null) {
          //   state.showJiFen = false;
          // } else {
          //   state.showJiFen = event['integral']['usr_point'] > 0;
          // }
          state.settData = event;
          if (event["settle_shop_item_list"] == null) {
            state.goodsItem = [];
          } else {
            state.goodsItem = event["settle_shop_item_list"];
          }
          state.number = 0;
          state.goodsItem.forEach((element) {
            if (element['ec_packages'] != null) {
              element['ec_packages'].forEach((item) {
                if (item['cartitemlist'] != null) {
                  item['cartitemlist'].forEach((itm) {
                    int num = itm['quantity'].toInt();
                    state.number += num;
                    print(num);
                  });
                }
              });
            }
          });

          state.isCoupons = event["able_discount_coupons"];
          if (event["able_discount_coupons"] != null) {
            List arr = event["able_discount_coupons"];

            arr.forEach((element) {
              if (element['show_status'] == 1) {
                state.couponName = element['qname'];
                state.couponData = element;
              }
            });
          }
          if (event["able_cash_coupons"] != null) {
            List arr1 = event["able_cash_coupons"];
            arr1.forEach((element) {
              if (element['show_status'] == 1) {
                state.couponName = element['qname'];
                state.couponData = element;
              }
            });
          }
          if (event["able_freight_coupons"] != null) {
            List arr2 = event["able_freight_coupons"];
            arr2.forEach((element) {
              if (element['show_status'] == 1) {
                state.couponName = element['qname'];
                state.couponData = element;
              }
            });
          }

          setcouponArr(event);
          update();
        });
        update();
      }
    });
  }

  ///获取礼品卡
  void getGiftCard() {
    var params = {
      "use_platform": 2,
      "usr_num_id": SpUtil.getInt('empeNumId'),
      'access_token': SpUtil.getString('token'),
      "card_status": 3, //购物卡状态 (1: 有效, 2:失效, 3: 可用)
    };
    Api.walletInformation(params).listen((event) {
      state.GiftcardList = event['available_cards'];
      state.GiftcardList.forEach((element) {
        element['click'] = false;
      });
      update();
    });
  }

  clickGift(index) {
    setcard(state, index);
    // state.isGiftMoney=10;
    update();
  }

  bool panduan() {
    if (state.orderAddress == null || state.orderAddress['prv_name'] == null) {
      toast("请选择地址");
      return false;
    }
    return true;
  }

  void selectCoupon(index, item) {
    // var clostate =  state.couponList[index]['show_status'];
    // state.couponList.forEach((element) {
    //
    //  });
    bool iss = panduan();
    if (iss) {
      state.couponData = item;

      if (state.couponList[index]['show_status'] == 1) {
        state.couponList[index]['show_status'] = 3;
        state.couponData['show_status'] = 3;
      } else {
        state.couponList[index]['show_status'] = 1;
        state.couponData['show_status'] = 1;
      }
      if (state.couponData['show_status'] == 3) {
        state.couponName = '';
      }
      if (state.couponList[index]['show_status'] == 1) {
        state.couponName = item['qname'];
        state.couponId = item['activityid'];
        state.qmz = item['qmz'];
      }
      update();
      submitCoupon();
    }
  }

  void submitCoupon() {
    var item = state.couponData;
    var params = {
      "usr_num_id": SpUtil.getInt('empeNumId'),
      "use_platform": 2,
      'access_token': SpUtil.getString('token'),
      "tran_type_num_id": 3,
      "prv_num_id": state.isZiTi ? state.a : state.orderAddress['prv_num_id'],
      "city_num_id": state.isZiTi ? state.b : state.orderAddress['city_num_id'],
      "city_area_num_id":
          state.isZiTi ? state.c : state.orderAddress['city_area_num_id'],
      "town_num_id": state.isZiTi ? state.d : state.orderAddress['town_num_id'],
      "maplocation_x": state.isZiTi
          ? state.maplocationX
          : state.orderAddress['maplocation_x'],
      "maplocation_y": state.isZiTi
          ? state.maplocationY
          : state.orderAddress['maplocation_y'],
      "adr_num_id": state.isZiTi
          ? state.sub_unit_num_id
          : state.orderAddress["adr_num_id"],
      'is_switch': 1,
      //使用积分传数值
      "integral": state.isJiFen ? null : 0,

      "adr_type": state.isZiTi ? 1 : 0,
      "is_logistics_cart": '1',
    };
    print('state.orderAddress["adr_num_id"]');
    print(state.isZiTi);
    print(state.orderAddress["adr_num_id"]);
    if (item['show_status'] == 3) {
      params['select_discount_coupons'] = [];
      params['select_cash_coupons'] = [];
      params['select_freight_coupons'] = [];
    } else {
      if (item['type'] == 1) {
        params['select_discount_coupons'] = [
          {'ticket_id': item['activityid'], 'coupon_no': item['qbarcode']}
        ];
      } else if (item['type'] == 2) {
        params['select_cash_coupons'] = [
          {'ticket_id': item['activityid'], 'coupon_no': item['qbarcode']}
        ];
      } else {
        params['select_freight_coupons'] = [
          {'ticket_id': item['activityid'], 'coupon_no': item['qbarcode']}
        ];
      }
    }

    Api.orderSettle(params).listen((event) {
      // 默认地址信息
      var params1 = {
        'usr_num_id': SpUtil.getInt('empeNumId'),
        'access_token': SpUtil.getString('token'),
      };

      // if (state.jiaAddress != null) {
      //   state.orderAddress = state.jiaAddress;
      // }
      state.settData = event;

      if (event["settle_shop_item_list"] == null) {
        state.goodsItem = [];
      } else {
        state.goodsItem = event["settle_shop_item_list"];
      }
      state.number = 0;
      state.goodsItem.forEach((element) {
        if (element['ec_packages'] != null) {
          element['ec_packages'].forEach((item) {
            if (item['cartitemlist'] != null) {
              item['cartitemlist'].forEach((itm) {
                int num = itm['quantity'].toInt();
                state.number += num;
                print(num);
              });
            }
          });
        }
      });

      state.isCoupons = event["able_discount_coupons"];
      setcouponArr(event);
      update();
    });
  }

  ///设置优惠卷
  void setcouponArr(event) {
    List newarr = [];
    List nonewarr = [];
    if (event["able_discount_coupons"] != null) {
      List arr = event["able_discount_coupons"];
      arr.forEach((element) {
        element['type'] = 1;
      });
      arr.forEach((element) {
        newarr.add(element);
      });
    }
    if (event["able_cash_coupons"] != null) {
      List arr1 = event["able_cash_coupons"];
      arr1.forEach((element) {
        element['type'] = 2;
      });
      arr1.forEach((element) {
        newarr.add(element);
      });
    }
    if (event["able_freight_coupons"] != null) {
      List arr2 = event["able_freight_coupons"];
      arr2.forEach((element) {
        element['type'] = 3;
      });
      arr2.forEach((element) {
        newarr.add(element);
      });
    }

    if (event["disable_discount_coupons"] != null) {
      List arr3 = event["disable_discount_coupons"];

      arr3.forEach((element) {
        nonewarr.add(element);
      });
    }
    if (event["disable_cash_coupons"] != null) {
      List arr4 = event["disable_cash_coupons"];

      arr4.forEach((element) {
        nonewarr.add(element);
      });
    }
    if (event["disable_freight_coupons"] != null) {
      List arr5 = event["disable_freight_coupons"];

      arr5.forEach((element) {
        nonewarr.add(element);
      });
    }
    state.couponList.clear();
    state.couponList.addAll(newarr);
    state.couponList.addAll(nonewarr);
    // state.couponList = newarr;
    state.nocouponList = nonewarr;
    if (event['total'] == null) {
      state.isStop = false;
      state.total = {
        'all_payment': 0.0,
        'all_fee': 0.0,
        'after_pro_fee': 100.0,
        'total_material_fee': 0.0,
        'freight_fee': 1.0,
        'actual_freight': 1.0,
        'total_discount_fee': 0.0,
        'coupon_discount': 0.0,
        'integral_discount': 0.0,
        'part_integral_discount': 0.0,
        'promotion_total_discount': 0.0,
        'ist_amount': 0.0,
        'deducts': null,
        'header_sales': null,
        'usr_point': null
      };
    } else {
      state.isStop = true;
      state.total = event["total"];
    }

    print('state.total');
    print(state.total);
    state.iscou = true;
    update();
  }

  void selectSwitch() {
    state.isJiFen = !state.isJiFen;
    // print('orderAddressorderAddressorderAddressorderAddressorderAddressorderAddress');
    //   print( state.orderAddress);
    if (state.orderAddress == null) {
      toast('请选择地址');
    }

    var params = {
      "usr_num_id": SpUtil.getInt('empeNumId'),
      // "emp_num_id": SpUtil.getInt('empeNumId'),
      "use_platform": 2,
      'is_switch': 1,
      "tran_type_num_id": 3,
      "prv_num_id": state.isZiTi ? state.a : state.orderAddress['prv_num_id'],
      "city_num_id": state.isZiTi ? state.b : state.orderAddress['city_num_id'],
      "city_area_num_id":
          state.isZiTi ? state.c : state.orderAddress['city_area_num_id'],
      "town_num_id": state.isZiTi ? state.d : state.orderAddress['town_num_id'],
      "maplocation_x": state.isZiTi
          ? state.maplocationX
          : state.orderAddress['maplocation_x'],
      "maplocation_y": state.isZiTi
          ? state.maplocationY
          : state.orderAddress['maplocation_y'],
      "adr_num_id": state.isZiTi
          ? state.sub_unit_num_id
          : state.orderAddress["adr_num_id"],
      //使用积分传数值
      "integral": state.isJiFen ? null : 0,

      "adr_type": state.isZiTi ? 1 : 0,
      'access_token': SpUtil.getString('token'),
      "is_logistics_cart": '1',
    };
    var item = state.couponData;

    if (item != null) {
      if (item['show_status'] == 3) {
        params['select_discount_coupons'] = [];
        params['select_cash_coupons'] = [];
        params['select_freight_coupons'] = [];
      } else {
        if (item['type'] == 1) {
          params['select_discount_coupons'] = [
            {'ticket_id': item['activityid'], 'coupon_no': item['qbarcode']}
          ];
        } else if (item['type'] == 2) {
          params['select_cash_coupons'] = [
            {'ticket_id': item['activityid'], 'coupon_no': item['qbarcode']}
          ];
        } else {
          params['select_freight_coupons'] = [
            {'ticket_id': item['activityid'], 'coupon_no': item['qbarcode']}
          ];
        }
      }
    } else {
      params['is_switch'] = 0;
    }

    print(">>>>>>>>@@@@@>>>>>>>$params");
    Api.orderSettle(params).listen((event) {
      if (event['code'] == 0) {
        print(">>>>>>>>>>>>>>>$event");
        // state.dianAdr = '${event['prv_name']}${event['city_name']}${event['city_area_name']}${event['adr']}' ;
        // if (state.orderAddress != null) {
        //   state.orderAddress = event["member_adr"];
        // }
        state.settData = event;

        if (event["settle_shop_item_list"] == null) {
          state.goodsItem = [];
        } else {
          state.goodsItem = event["settle_shop_item_list"];
        }
        state.number = 0;
        state.goodsItem.forEach((element) {
          if (element['ec_packages'] != null) {
            element['ec_packages'].forEach((item) {
              if (item['cartitemlist'] != null) {
                item['cartitemlist'].forEach((itm) {
                  int num = itm['quantity'].toInt();
                  state.number += num;
                  print(num);
                });
              }
            });
          }
        });

        state.isCoupons = event["able_discount_coupons"];
        List newarr = [];
        setcouponArr(event);

        update();
      }
    });
  }

  void selectSwitch1() {
    var params = {
      "usr_num_id": SpUtil.getInt('empeNumId'),
      'access_token': SpUtil.getString('token'),
      "use_platform": 2,
      "tran_type_num_id": 3,
      "prv_num_id": state.orderAddress['prv_num_id'],
      "city_num_id": state.orderAddress['city_num_id'],
      "city_area_num_id": state.orderAddress['city_area_num_id'],
      "town_num_id": state.orderAddress['town_num_id'],
      "maplocation_x": state.orderAddress['maplocation_x'],
      "maplocation_y": state.orderAddress['maplocation_y'],
      "adr_num_id": state.orderAddress["adr_num_id"],
      //使用积分传数值
      "integral": state.isJiFen ? null : 0,

      "adr_type": 0,
      "is_logistics_cart": '1',
    };
    var item = state.couponData;
    print('输出输出输出输出输出输出输出输出输出输出输出输出');
    print(state.orderAddress);
    if (item != null) {
      if (item['show_status'] == 3) {
        params['select_discount_coupons'] = [];
        params['select_cash_coupons'] = [];
        params['select_freight_coupons'] = [];
      } else {
        if (item['type'] == 1) {
          params['select_discount_coupons'] = [
            {'ticket_id': item['activityid'], 'coupon_no': item['qbarcode']}
          ];
        } else if (item['type'] == 2) {
          params['select_cash_coupons'] = [
            {'ticket_id': item['activityid'], 'coupon_no': item['qbarcode']}
          ];
        } else {
          params['select_freight_coupons'] = [
            {'ticket_id': item['activityid'], 'coupon_no': item['qbarcode']}
          ];
        }
      }
    } else {
      params['is_switch'] = 0;
    }
    Api.orderSettle(params).listen((event) {
      // if (state.orderAddress != null) {
      //   state.orderAddress = event["member_adr"];
      // }
      state.settData = event;

      if (event["settle_shop_item_list"] == null) {
        state.goodsItem = [];
      } else {
        state.goodsItem = event["settle_shop_item_list"];
      }
      state.number = 0;
      state.goodsItem.forEach((element) {
        if (element['ec_packages'] != null) {
          element['ec_packages'].forEach((item) {
            if (item['cartitemlist'] != null) {
              item['cartitemlist'].forEach((itm) {
                int num = itm['quantity'].toInt();
                state.number += num;
                print(num);
              });
            }
          });
        }
      });

      state.isCoupons = event["able_discount_coupons"];
      setcouponArr(event);
      update();
    });
  }

  void selectDian(int i, item) {
    print('>>>>>>>>>$item');
    state.selected = i;
    state.a = item['prv_num_id'];
    state.b = item['city_num_id'];
    state.c = item['city_area_num_id'];
    state.d = item['town_num_id'];
    state.maplocationX = item['maplocation_x'];
    state.maplocationY = item['maplocation_y'];
    state.sub_unit_num_id = item['sub_unit_num_id'];
    state.dianAdr = item['prv_name'] +
        item['city_name'] +
        item['city_area_name'] +
        item['adr'];
    var params = {
      "usr_num_id": SpUtil.getInt('empeNumId'),
      // "emp_num_id": SpUtil.getInt('empeNumId'),
      "use_platform": 2,

      "tran_type_num_id": 3,
      "prv_num_id": state.a,
      "city_num_id": state.b,
      "city_area_num_id": state.c,
      "town_num_id": state.d,
      "maplocation_x": state.maplocationX,
      "maplocation_y": state.maplocationY,
      "adr_num_id": state.sub_unit_num_id,
      "adr_type": 1,
      'is_switch': 1,
      'access_token': SpUtil.getString('token'),
      "is_logistics_cart": '1',
    };
    var items = state.couponData;
    if (items != null) {
      if (items['show_status'] == 3) {
        params['select_discount_coupons'] = [];
        params['select_cash_coupons'] = [];
        params['select_freight_coupons'] = [];
      } else {
        if (items['type'] == 1) {
          params['select_discount_coupons'] = [
            {'ticket_id': items['activityid'], 'coupon_no': items['qbarcode']}
          ];
        } else if (items['type'] == 2) {
          params['select_cash_coupons'] = [
            {'ticket_id': items['activityid'], 'coupon_no': items['qbarcode']}
          ];
        } else {
          params['select_freight_coupons'] = [
            {'ticket_id': items['activityid'], 'coupon_no': items['qbarcode']}
          ];
        }
      }
    } else {
      params['is_switch'] = 0;
    }
    Api.orderSettle(params).listen((event) {
      // state.orderAddress = event["member_adr"];
      state.settData = event;

      if (event["settle_shop_item_list"] == null) {
        state.goodsItem = [];
      } else {
        state.goodsItem = event["settle_shop_item_list"];
      }
      state.number = 0;
      state.goodsItem.forEach((element) {
        if (element['ec_packages'] != null) {
          element['ec_packages'].forEach((item) {
            if (item['cartitemlist'] != null) {
              item['cartitemlist'].forEach((itm) {
                int num = itm['quantity'].toInt();
                state.number += num;
                print(num);
              });
            }
          });
        }
      });

      setcouponArr(event);
      update();
    });
    update();
  }

  void submitDian() {
    if (!state.iszitibutton) {
      return;
    }
    state.isZiTi = true;
    state.adr = state.dianAdr;
    int index = state.selected;
    var item = state.selfHelpAddressList[index];
    state.a = item['prv_num_id'];
    state.b = item['city_num_id'];
    state.c = item['city_area_num_id'];
    state.d = item['town_num_id'];
    state.maplocationX = item['maplocation_x'];
    state.maplocationY = item['maplocation_y'];
    state.sub_unit_num_id = item['sub_unit_num_id'];
    state.dianAdr = item['prv_name'] +
        item['city_name'] +
        item['city_area_name'] +
        item['adr'];
    var params = {
      "usr_num_id": SpUtil.getInt('empeNumId'),
      // "emp_num_id": SpUtil.getInt('empeNumId'),
      "use_platform": 2,
      "tran_type_num_id": 3,
      "prv_num_id": state.a,
      "city_num_id": state.b,
      "city_area_num_id": state.c,
      "town_num_id": state.d,
      "maplocation_x": state.maplocationX,
      "maplocation_y": state.maplocationY,
      "adr_num_id": state.sub_unit_num_id,
      "adr_type": 1,
      'is_switch': 1,
      "integral": state.isJiFen ? null : 0,
      'access_token': SpUtil.getString('token'),
      "is_logistics_cart": '1',
    };
    var items = state.couponData;
    // print('state.couponData state.couponData state.couponData state.couponData');
    // print(items);
    // return;
    if (items != null) {
      if (item['show_status'] == 3) {
        params['select_discount_coupons'] = [];
        params['select_cash_coupons'] = [];
        params['select_freight_coupons'] = [];
      } else if (item['show_status'] == 1) {
        if (items['type'] == 1) {
          params['select_discount_coupons'] = [
            {'ticket_id': items['activityid'], 'coupon_no': items['qbarcode']}
          ];
        } else if (item['type'] == 2) {
          params['select_cash_coupons'] = [
            {'ticket_id': items['activityid'], 'coupon_no': items['qbarcode']}
          ];
        } else {
          params['select_freight_coupons'] = [
            {'ticket_id': items['activityid'], 'coupon_no': items['qbarcode']}
          ];
        }
      } else {
        params['select_discount_coupons'] = [];
        params['select_cash_coupons'] = [];
        params['select_freight_coupons'] = [];
      }
    } else {
      params['is_switch'] = 0;
    }
    print('入参数');
    print(params);
    Api.orderSettle(params).listen((event) {
      state.isZiTi = true;
      state.settData = event;
      // state.orderAddress = event["member_adr"];

      if (event["settle_shop_item_list"] == null) {
        state.goodsItem = [];
      } else {
        state.goodsItem = event["settle_shop_item_list"];
      }
      state.number = 0;
      state.goodsItem.forEach((element) {
        if (element['ec_packages'] != null) {
          element['ec_packages'].forEach((item) {
            if (item['cartitemlist'] != null) {
              item['cartitemlist'].forEach((itm) {
                int num = itm['quantity'].toInt();
                state.number += num;
                print(num);
              });
            }
          });
        }
      });

      state.isCoupons = event["able_discount_coupons"];
      state.isCoupons = event["able_discount_coupons"];
      setcouponArr(event);
      update();
    });
    update();
  }

  void selfHelpAddress() {
    state.selfHelpAddressList = [];
    var params = {
      'is_pick_up': 1,

      "prv_num_id": state.orderAddress['prv_num_id'],
      "city_num_id": state.orderAddress['city_num_id'],
      "city_area_num_id": state.orderAddress['city_area_num_id'],
      "town_num_id": state.orderAddress['town_num_id'],
      "maplocation_x": state.orderAddress['maplocation_x'],
      "maplocation_y": state.orderAddress['maplocation_y'],
      "adr_num_id": state.orderAddress["adr_num_id"],

      "page": 1,
      "page_size": 10,
      // 'usr_num_id': SpUtil.getInt('empeNumId')
    };
    print('自提点自提点自提点自提点自提点自提点');
    print(params);
    Api.selfHelpAddress(params).listen((event) {
      if (event['sub_unit_shop_list'].length > 0) {
        state.iszitibutton = true;
        state.selfHelpAddressList = event['sub_unit_shop_list'];
        var item = event['sub_unit_shop_list'][0];
        state.dianAdr = item['prv_name'] +
            item['city_name'] +
            item['city_area_name'] +
            item['adr'];
      } else {
        state.iszitibutton = false;
      }

      update();
    });
  }

  //结算页优惠券选择
  void orderCouponSelect() {
    var params = {
      "usr_num_id": SpUtil.getString('userNumId'),
      "emp_num_id": SpUtil.getInt('empeNumId'),
      "use_platform": 2,
      "tran_type_num_id": 3,
      "adr_type": 0,
    };
    Api.orderCouponSelect(params).listen((event) {
      update();
    });
  }

  /// 选择支付方式
  void setPayType(int index) {
    state.paytype = index;
    update();
  }

  /// 选择尾款预计付款时间
  void selectDate(DateTime value) {
    state.time = value;
    state.time1 = '${DateFormat("yyyy-MM-dd").format(value)}';
    update();
  }

  /// 输入订金计算尾款
  void countMoney(value) {
    if (!isNumber(value)) {
      state.controller1.clear();
      state.endMoney = null;
      state.startMoney = null;
      return;
    } else if (double.parse(value.toString().isEmpty ? '0' : value) < 0) {
      toast('定金金额不能小于0');
      state.controller1.clear();
      state.startMoney = null;
      state.endMoney = null;
      update();
    } else if (double.parse(value.toString().isEmpty ? '0' : value) >
        state.total["all_payment"]) {
      toast('定金金额不能大于商品金额');
      state.controller1.clear();
      state.startMoney = null;
      state.endMoney = null;
      update();
    } else {
      var dj = double.parse(value.toString().isEmpty ? '0' : value);
      var money = state.total["all_payment"] - dj;
      state.endMoney =
          (NumUtil.getNumByValueDouble(money, 2)).toStringAsFixed(2); // 保留两位小数
      state.startMoney =
          (NumUtil.getNumByValueDouble(dj, 2)).toStringAsFixed(2); // 保留两位小数
    }
    update();
  }

  bool isNumber(String value) {
    if (value == null) {
      return true;
    }
    final n = num.tryParse(value);
    return n != null;
  }

  //提交订单数据
  void orderSubmit() {
    if (state.orderAddress == null) {
      toast("请选择地址");
      return;
    }

    List cartitemlist = [];
    state.goodsItem.forEach((index) {
      index["ec_packages"].forEach((index1) {
        index1["cartitemlist"].forEach((index2) {
          var dataItem = {
            "cart_id": index2["cart_id"],
            "shop_id": index2["shop_id"],
            "item_num_id": index2["item_num_id"],
            "is_checked": index2["is_checked"],
            "obj_type": index2["obj_type"],
            "user_id": index2["user_id"],
            "quantity": index2["quantity"],
            "title": index2["title"],
            "created_time": index2["created_time"].split(' ')[0],
            "image_default_id": index2["image_default_id"],
            // "ec_style_num_id":
            //     index1["ec_style_num_id"] ?? index2["ec_style_num_id"],
            "ec_style_num_id": index1["ec_style_num_id"],
            "style_num_id": index2["style_num_id"],
          };
          cartitemlist.add(dataItem);
        });
      });
    });

    var params;
    var type = state.paytype;
    if (state.startMoney == null && type == 2) {
      toast('请输入订金金额');
      return;
    }
    if (state.time1 == '' && type == 2) {
      toast('请选择尾款预计付款日期');
      return;
    }

    params = {
      "use_platform": 2,
      "usr_num_id": SpUtil.getInt('empeNumId'),
      // "emp_num_id": SpUtil.getInt('empeNumId'),
      //省市区

      "prv_num_id": state.isZiTi ? state.a : state.orderAddress['prv_num_id'],
      "city_num_id": state.isZiTi ? state.b : state.orderAddress['city_num_id'],
      "city_area_num_id":
          state.isZiTi ? state.c : state.orderAddress['city_area_num_id'],
      "town_num_id": state.isZiTi ? state.d : state.orderAddress['town_num_id'],
      "maplocation_x": state.isZiTi
          ? state.maplocationX
          : state.orderAddress['maplocation_x'],
      "maplocation_y": state.isZiTi
          ? state.maplocationY
          : state.orderAddress['maplocation_y'],
      "adr_num_id": state.isZiTi
          ? state.sub_unit_num_id
          : state.orderAddress["adr_num_id"],
      "customer_order_type": 0,
      //自提默认零
      "adr_type": state.isZiTi ? 1 : 0,
      'consumer_name': state.orderAddress["cont_empe"],
      'consumer_telephone': state.orderAddress["contact_no"],
      //使用积分传数值
      "integral": state.isJiFen ? null : 0,
      //客户备注
      "buyer_memo": state.controller.text,
      //配送方式
      // "tran_type_num_id":state.deliveryType,
      "tran_type_num_id": 3,
      //tml_type	Integer	是	0	发货类型:0:立即发货,1 预约发货,2 暂不发货
      "tml_type": state.deliveryType,
      //发货开始时间
      "delivery_start_time": state.dateTime.toString().split(' ')[0],
      // 提交类型submit_type	Integer	是	0	提交类型：0 普通结算, 1 立即购买
      "submit_type": 0,
      'activityid': state.couponId,
      "so_sign": 0,
      'channel_num_id': '99',
      //商品信息
      "cart_item_list": cartitemlist,
      'access_token': SpUtil.getString('token'),
      // 'ec_shop_num_id': SpUtil.getInt('storeShopNum'), //店铺ID
      "ec_shop_num_id": SpUtil.getObject(Config.GET_SHOP_INFO)['shop_id'],
      "invoice_main": state.p,
      "is_logistics_cart": '1',
    };

    // toast("发票内容");

    // return;
    // // print(state.p);
    // // return;
    print("发票内容=${state.p}");
    print(">>>>>>>>>>>1133322231111111");

    var item = state.couponData;
    if (item != null) {
      if (item['show_status'] == 3) {
        params['select_discount_coupons'] = [];
        params['select_cash_coupons'] = [];
        params['select_freight_coupons'] = [];
      } else {
        if (item['type'] == 1) {
          params['select_discount_coupons'] = [
            {'ticket_id': item['activityid'], 'coupon_no': item['qbarcode']}
          ];
        } else if (item['type'] == 2) {
          params['select_cash_coupons'] = [
            {'ticket_id': item['activityid'], 'coupon_no': item['qbarcode']}
          ];
        } else {
          params['select_freight_coupons'] = [
            {'ticket_id': item['activityid'], 'coupon_no': item['qbarcode']}
          ];
        }
      }
    }

    if (state.total["all_payment"] == 0) {
      Api.orderSubmit(params).listen((event) {
        if (event["code"] == 0) {
          var params1 = {
            "out_trade_no": event["tml_num_id"].toString(),
            "plat_type": 7,
            "body": "jifen",
            "pay_way": 0,
            'access_token': SpUtil.getString('token'),
            'appid': 'wxf6e85f0b41014cda',
            // 'ec_shop_num_id': SpUtil.getInt('storeShopNum'),
            "ec_shop_num_id": SpUtil.getObject(Config.GET_SHOP_INFO)['shop_id'],
          };
          SpUtil.putString('pay_type', 'list');
          SpUtil.putDouble('need_pay_amount', event['need_pay_amount']);
          SpUtil.putString('tml_num_id', event['tml_num_id']);
          state.total["all_payment"] = event['need_pay_amount'];
          Api.orderPayment(params1).listen((event) {
            // toast(event["message"]);

            SpUtil.putString('dingdan', event['tml_num_id']);
            state.shifu = event['pay_response']['coupon_fee'];
            setMoneyOver(
                SpUtil.getString('dingdan'), 1, 'Complete', 'success', 'a');
          });
        } else {
          state.disable = true;
          toast(event["message"]);
          update();
        }
      });
    } else {
      // toast("发票内容=${state.p}");

      // return;
      Api.orderSubmit(params).listen((event) {
        // toast(event["message"]);
        if (event["code"] == 0) {
          state.total["all_payment"] = event['need_pay_amount'];
          SpUtil.putDouble('need_pay_amount', event['need_pay_amount']);
          SpUtil.putString('tml_num_id', event['tml_num_id']);
          var params1;
          if (kIsWeb == true) {
            params1 = {
              "out_trade_no": event["tml_num_id"].toString(),
              "plat_type": 7,
              "body": "jifen",
              "pay_way": 0,
              "use_platform": 1,
              'access_token': SpUtil.getString('token'),
              // 'appid': 'wxf6e85f0b41014cda',
            };
          } else {
            params1 = {
              "out_trade_no": event["tml_num_id"].toString(),
              "plat_type": 7,
              "body": "jifen",
              "pay_way": 0,
              "use_platform": Config.use_plat_form,
              'access_token': SpUtil.getString('token'),
              'appid': Config.ZJ_APPID,
            };
          }
          state.total["all_payment"] = event['need_pay_amount'];
          // return;
          if (state.GiftcardList.length > 0) {
            gotomoney(state, startCPCNWeixinPay, params1,
                event["tml_num_id"].toString());
          } else {
            Api.orderPayment(params1).listen((event2) {
              if (event2['code'] == 0) {
                print('预支付滴滴滴滴滴');
                print(event2);
                SpUtil.putString('dingdan', event['tml_num_id']);
                state.shifu = event2['pay_response']['coupon_fee'];
                if (kIsWeb == true) {
                  webpay(event2['pre_pay_no']);
                } else {
                  startCPCNWeixinPay(event2['pre_pay_no']);
                }
              } else {
                toast(event2['message']);
              }
            });
          }
        } else {
          state.disable = true;
          toast(event["message"]);
          update();
        }
      });
    }
  }

  /// 拉起中金支付
  void startCPCNWeixinPay(String authCode) async {
    if (authCode.isEmpty) {
      toast("签名失败");
      return;
    }
    var result =
        await fluwx.payWithCPCN(appId: Config.WECHAT_APPID, authCode: authCode);

    // var result = fluwx.openWeChatApp();

    print("=========结果<<<$result>>>====");
  }
}
